package com.qunar.sy.demo.controller;

import com.qunar.sy.demo.model.User;
import com.qunar.sy.demo.response.BaseResponse;
import com.qunar.sy.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index() {
        return "hello";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public BaseResponse list() {
        List<User> userList = userService.selectAll();
        return BaseResponse.success(userList);
    }

    @GetMapping("/getById/{id}")
    public BaseResponse getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return BaseResponse.success(user);
    }

    @GetMapping("/getById2")
    public BaseResponse getById2(@RequestParam(name = "id", required = false) Integer id) {
        if (id == null) {
            return BaseResponse.fail("没传id");
        }
        User user = userService.getById(id);
        return BaseResponse.success(user);
    }

    @PostMapping("/save")
    public BaseResponse save(@RequestBody User user) {
        if (user.getUserName() == null || user.getUserName().equals("")) {
            return BaseResponse.fail("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().equals("")) {
            return BaseResponse.fail("密码不能为空");
        }
        userService.save(user);
        return BaseResponse.success(null);
    }
    @DeleteMapping("/delete/{id}")
    public BaseResponse delete(@PathVariable Integer id) {
        userService.delete(id);
        return BaseResponse.success(null);
    }
}
